import { Popup, Tabs, Toast } from 'antd-mobile';
import {
  addUserChannel,
  delUserChannelAction,
  getAllChannel,
  getUserChannel,
  setChannelIdAction,
} from '@/store/action/channel';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useAppSelector } from '@/store';
import Icon from '../Icon';
import styles from './index.module.scss';
import lodash from 'lodash';
import { ChannelType } from '@/store/reducers/channel';
import { useHistory } from 'react-router-dom';

// 切换编辑模式
// 频道高亮处理
// 添加频道
// 情况1：未登录，去缓存中读取频道列表
// 情况2： 登录后，发送请求获取频道
export default function Channel() {
  const history = useHistory();
  const { userList, channelList, channel_id } = useAppSelector(
    (state) => state.channel
  );
  const [visible, setVisible] = useState(false);
  //   切换编辑模式
  const [editable, setEditable] = useState(false);
  //   注意是子字符串零
  // const [activeId, setActiveId] = useState('0'); //改造到reducer
  // const [activeId, setActiveId] = useState('0');

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getAllChannel());
    dispatch(getUserChannel());
  }, [dispatch]);
  //  第一种方法计算属性
  //   const restList = channelList.filter((item) => {
  //     // 对象中可以用findIndex
  //     return userList.findIndex((v) => v.id === item.id) === -1;
  //   });
  //   console.log(userList, 14);
  // 第二种方法
  const restList = lodash.differenceBy(channelList, userList, 'id');
  // 添加频道
  const handleAddFn = async (item: ChannelType) => {
    await dispatch(addUserChannel(item));
    Toast.show({ content: '更新成功' });
  };
  // 删除
  const handleDelFn = async (id: number) => {
    if (userList.length <= 5) return Toast.show({ content: '频道不能小于5' });
    if (id === 0) return Toast.show({ content: '推荐不能删除' });
    await dispatch(delUserChannelAction(id));
    Toast.show({ content: '删除成功' });
  };
  // 关闭弹窗与X
  const handleShowFn = () => {
    setVisible(false);
    setEditable(false);
  };
  return (
    <div className={styles.root}>
      <Tabs
        className="tabs"
        // 改造到reducer中
        activeKey={String(channel_id)}
        onChange={(key) => dispatch(setChannelIdAction(Number(key)))}
      >
        {userList.map((item) => {
          return <Tabs.Tab title={item.name} key={item.id}></Tabs.Tab>;
        })}
      </Tabs>
      <div className="right">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>
      <Popup
        visible={visible}
        position="left"
        bodyClassName={styles.channelPopup}
      >
        {/* 顶部栏：带关闭按钮 */}
        <div className="channel-header">
          <Icon type="iconbtn_channel_close" onClick={handleShowFn} />
        </div>

        {/* 频道列表 */}
        <div className="channel-content">
          {/* 当前已选择的频道列表 */}
          <div className="channel-item edit">
            <div className="channel-item-header">
              <span className="channel-item-title">我的频道</span>
              <span className="channel-item-title-extra">点击删除频道</span>
              <span
                className="channel-item-edit"
                onClick={() => setEditable(!editable)}
              >
                {editable ? '完成' : '编辑'}
              </span>
            </div>

            <div className="channel-list">
              {userList.map((item) => {
                return (
                  <span className="channel-list-item" key={item.id}>
                    {item.name}
                    {editable && (
                      <Icon
                        type="iconbtn_tag_close"
                        onClick={() => handleDelFn(item.id)}
                      />
                    )}
                  </span>
                );
              })}
            </div>
          </div>

          {/* 推荐的频道列表 */}
          <div className="channel-item">
            <div className="channel-item-header">
              <span className="channel-item-title">频道推荐</span>
              <span className="channel-item-title-extra">点击添加频道</span>
            </div>
            <div className="channel-list">
              {restList.map((item) => {
                return (
                  <span
                    className="channel-list-item"
                    key={item.id}
                    onClick={() => handleAddFn(item)}
                  >
                    {item.name}
                  </span>
                );
              })}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  );
}
